<template>
  <div :class="prefixCls">
    <a-row :class="`${prefixCls}-top`">
      <a-col :span="6" :class="`${prefixCls}-col`">
        <div :class="`${prefixCls}-top__logo`">
          <img width="160" height="160" :src="logoImage" />
          <div class="mt-2">
            <!-- <Authority :value="'Root.Admin.Systems.Logo.UploadLogo'"> -->
            <Authority>
              <Upload
                :showUploadList="false"
                :loading="loading"
                :accept="logoFormat"
                :beforeUpload="handleUploadLogo"
              >
                <Button preIcon="ant-design:cloud-upload-outlined" type="primary">
                  {{ t('common.updateText') }}
                </Button>
              </Upload>
            </Authority>
            <!-- <Authority :value="'Root.Admin.Systems.Logo.DeleteLogo'"> -->
            <Authority>
              <Button
                preIcon="bx:reset"
                type="primary"
                danger
                class="ml-2"
                @click="handleResetLogo"
              >
                {{ t('common.resetText') }}
              </Button>
            </Authority>
          </div>
        </div>
      </a-col>
      <a-col :span="8" :class="`${prefixCls}-col`">
        <CollapseContainer :title="t('routes.system.preference.appTitleText')" :canExpand="false">
          <Input
            size="large"
            v-model:value="appTitle"
            :placeholder="t('routes.system.preference.appTitleText')"
            class="fix-auto-fill"
            :allowClear="true"
          >
            <template #prefix>
              <Icon icon="fluent:app-title-24-regular" />
            </template>
          </Input>
          <a-row class="mt-2" justify="end">
            <Authority :value="'Root.Admin.Systems.Settings.SetAppTitle'">
              <Button preIcon="carbon:save" type="primary" @click="handleSetAppTitle">
                {{ t('common.saveText') }}
              </Button>
            </Authority>
          </a-row>
        </CollapseContainer>
      </a-col>
      <a-col :span="10" :class="`${prefixCls}-col`">
        <CollapseContainer
          :title="t('routes.system.preference.appDescriptionText')"
          :canExpand="false"
        >
          <Textarea
            size="large"
            v-model:value="appDescription"
            :placeholder="t('routes.system.preference.appDescriptionText')"
            class="fix-auto-fill"
            :allowClear="true"
            :auto-size="{ minRows: 1, maxRows: 1 }"
          />
          <Textarea
            size="middle"
            v-model:value="appSubdescription"
            :placeholder="t('routes.system.preference.appSubdescriptionText')"
            class="fix-auto-fill mt-1"
            :allowClear="true"
            :auto-size="{ minRows: 2, maxRows: 2 }"
          />
          <a-row class="mt-2" justify="end">
            <Authority :value="'Root.Admin.Systems.Settings.SetAppDescription'">
              <Button preIcon="carbon:save" type="primary" @click="handleSetAppDescription">
                {{ t('common.saveText') }}
              </Button>
            </Authority>
          </a-row>
        </CollapseContainer>
      </a-col>
    </a-row>
    <div :class="`${prefixCls}-bottom`">
      <Tabs v-model:activeKey="activeKey">
        <TabPane key="1" :tab="t('routes.system.preference.application.title')">
          <Application />
        </TabPane>
      </Tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { Tabs, Row, Col, Upload, Input, Textarea } from 'ant-design-vue';
  import { watch, computed, ref } from 'vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Authority } from '@/components/Authority';
  import { Button } from '@/components/Button/index';
  import { CollapseContainer } from '@/components/Container/index';
  import Icon from '@/components/Icon/Icon.vue';
  import Application from './Application.vue';

  // import { achieveList } from './data';

  import { usePreferenceStoreWithOut } from '@/store/modules/preference';

  const TabPane = Tabs.TabPane;
  const ARow = Row;
  const ACol = Col;

  defineOptions({ name: 'PreferencePage' });

  const activeKey = ref('1');
  const { t } = useI18n();
  const { createMessage } = useMessage();
  const preferenceStore = usePreferenceStoreWithOut();
  const loading = ref(false);
  const logoFormat = '.jpg,.jpeg,.png,.bmp,.ico,.gif';

  const logoImage = computed(() => preferenceStore.getLogo);
  const appTitle = ref(preferenceStore.getAppTitle);
  const appDescription = ref(preferenceStore.getAppDescription);
  const appSubdescription = ref(preferenceStore.getAppSubdescription);

  watch(
    () => preferenceStore.getAppTitle,
    (val) => {
      appTitle.value = val;
    },
    { immediate: true },
  );
  watch(
    () => preferenceStore.getAppDescription,
    (val) => {
      appDescription.value = val;
    },
    { immediate: true },
  );
  watch(
    () => preferenceStore.getAppSubdescription,
    (val) => {
      appSubdescription.value = val;
    },
    { immediate: true },
  );

  /** 处理上传LOGO */
  const handleUploadLogo = async (file: File) => {
    try {
      loading.value = true;
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/bmp' ||
        file.type === 'image/gif' ||
        file.type === 'image/x-icon';
      if (!isJpgOrPng) {
        createMessage.error(t('component.upload.acceptUpload', [logoFormat]));
        return isJpgOrPng;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        createMessage.error(t('component.upload.maxSize', '2'));
        return isLt2M;
      }
      const result = await preferenceStore.uploadLogo({ file, filename: file.name }, (_e) => {
        // console.log('uploadLogo', e);
      });
      if (result?.data?.Type === 200) {
        createMessage.success(t('common.successText'));
      }
    } finally {
      loading.value = false;
    }
    return false;
  };
  /** 处理重置LOGO */
  const handleResetLogo = async () => {
    try {
      loading.value = true;
      const result = await preferenceStore.resetLogo();
      if (result?.Type === 200) {
        createMessage.success(t('common.successText'));
      }
    } finally {
      loading.value = false;
    }
    return false;
  };

  /** 处理设置应用标题 */
  const handleSetAppTitle = async () => {
    try {
      loading.value = true;
      const result = await preferenceStore.setAppTitle(appTitle.value);
      if (result) {
        createMessage.success(t('common.successText'));
      }
    } finally {
      loading.value = false;
    }
    return false;
  };
  /** 处理设置应用描述 */
  const handleSetAppDescription = async () => {
    try {
      loading.value = true;
      let result = false;
      if (appDescription.value !== t('sys.login.signInTitle')) {
        result = await preferenceStore.setAppDescription(appDescription.value);
        if (result === false) {
          createMessage.error(t('common.errorText'));
        }
      }
      if (appDescription.value !== t('sys.login.signInDesc')) {
        result = await preferenceStore.setAppSubdescription(appSubdescription.value);
        if (result === false) {
          createMessage.error(t('common.errorText'));
        }
      }
      if (result) {
        createMessage.success(t('common.successText'));
      }
    } finally {
      loading.value = false;
    }
    return false;
  };

  const prefixCls = 'preference-setting';
</script>

<style lang="less" scoped>
  .preference-setting {
    &-col {
      padding: 0 10px;

      &:not(:last-child) {
        border-right: 1px dashed rgb(206 206 206 / 50%);
      }
    }

    &-top {
      margin: 16px 16px 12px;
      padding: 10px;
      border-radius: 3px;
      background-color: @component-background;

      &__logo {
        text-align: center;

        img {
          margin: auto;
          // border-radius: 50%;
        }
      }

      &__detail {
        margin-top: 15px;
        padding-left: 20px;
      }
    }

    &-bottom {
      margin: 0 16px 16px;
      padding: 10px;
      border-radius: 3px;
      background-color: @component-background;
    }
  }
</style>
